# -*- coding: utf-8 -*-
# @Time : 2022-03-31 9:40
# @Author : Z
# @Function :

from time import sleep

import cv2
import requests
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By


def FindPic(bg="", block=""):
    """
    找出图像中最佳匹配位置
    :param target: 目标即背景图
    :param template: 模板即需要找到的图
    :return: 返回最佳匹配及其最差匹配和对应的坐标
    """
    # 读取图片
    target_rgb = cv2.imread(bg)
    # 灰度处理
    target_gray = cv2.cvtColor(target_rgb, cv2.COLOR_BGR2GRAY)
    # 读取滑块
    template_rgb = cv2.imread(block, 0)
    # 匹配缺口在背景图的位置
    res = cv2.matchTemplate(target_gray, template_rgb, cv2.TM_CCOEFF_NORMED)
    # 获取最差和最佳的匹配
    value = cv2.minMaxLoc(res)
    print(value)
    # 返回最佳匹配的x坐标
    return value[2][0]


# 打开浏览器，进入登录页面
driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.get('https://im.qq.com')
driver.maximize_window()
driver.find_element(By.XPATH, '//*[@id="loginInfo"]/a').click()
driver.switch_to.frame(driver.find_element(By.XPATH, '//*[@name="frame-login"]'))
driver.find_element(By.XPATH, '//*[@id="switcher_plogin"]').click()
driver.find_element(By.XPATH, '//*[@id="u"]').send_keys('124913651')
driver.find_element(By.XPATH, '//*[@id="p"]').send_keys('123wsdf')
sleep(1)
driver.find_element(By.XPATH, '//*[@id="login_button"]').click()
driver.switch_to.frame(driver.find_element(By.XPATH, '//*[@id="tcaptcha_iframe"]'))

while True:
    # 获取图片地址
    sleep(3)
    ele_bj = driver.find_element(By.XPATH, '//*[@id="slideBg"]')
    src_bj = ele_bj.get_attribute('src')
    ele_block = driver.find_element(By.XPATH, '//*[@id="slideBlock"]')
    src_block = ele_block.get_attribute('src')

    # 下载图片并保存到本地
    img_bj = requests.get(src_bj).content
    f = open('../../lib/verify/bg.jpg', mode='wb')
    f.write(img_bj)
    f.close()

    img_block = requests.get(src_block).content
    f = open('../../lib/verify/block.jpg', mode='wb')
    f.write(img_block)
    f.close()

    # 获取最佳偏移距离
    x = FindPic('../../lib/verify/bg.jpg', '../../lib/verify/block.jpg')
    print("没有缩放的x的值" + str(x))

    a = ele_bj.size.get("width")
    print(a)
    x = int(x * a / 680) - 22
    print("缩放后的x值" + str(x))

    action = ActionChains(driver)
    action.click_and_hold(ele_block).perform()
    action.move_by_offset(x, 0).perform()
    sleep(1)
    action.release().perform()

    sleep(3)
    try:
        driver.find_element(By.XPATH, "//div[@id='e_reload' and @role]/img").click()
    except:
        break
